//
//  BPStatusCellViewModel.swift
//  BPWeiBo
//  Created by apple on 16/4/12.
//  Copyright © 2016年 apple. All rights reserved.
//对应的是每一个cell的值

import UIKit
import YYText
class BPStatusCellViewModel: NSObject {
    
    //设置parrent
    let parrentHuati = "#.*?#"
    let parrentAt = "@\\w+"
    let parrenturl = "(http[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?"
    let parrentEnmotion =  "\\[.*?\\]"
    
    //设置模型对象的属性
    var statusListModel : BPStatusListView?
    
    //定义头像的URL
    var headImgURl:NSURL?
    
    //用户的认证类型,认证类型 -1：没有认证，1：认证用户，2,3,5: 企业认证，220: 达人
    var verified_type:NSNumber?
    
    //用户的等级
    var mbrank:NSNumber?
    
    ///微博转发的数量
    var reposts_count:Int = 0
    ///微博评论的数量
    var comments_count:Int = 0
    ///微博点赞的数量
    var attitudes_count:Int = 0
    
    ///微博的来源
    var source:String?
    //微博时间  只读属性(计算型属性)
    var time: String? {
        return NSDate.sinaDate(statusListModel?.created_at ?? "")?.fullDescription()
    }
    
    //原创话题文字的属性文本
    var huatiAtteibute:NSMutableAttributedString?
    
    //转发微博话题文字的属性文本
    var zhuangfaAtt:NSMutableAttributedString?
    
    
    //重写模型对象的构造方法,设置一些数字能够
    
    init(status: BPStatusListView) {
        super.init()
        //记录参数
        self.statusListModel = status
        //给定义头像的URL赋值
        self.headImgURl = NSURL(string: (status.user?.profile_image_url)!)!
        //获取用户的类型
        self.verified_type = (status.user?.verified_type)!
        //获取用户的等级
        self.mbrank = status.user?.mbrank
        
        //获取转发量,评论数量,点赞的数量
        self.reposts_count = status.reposts_count
        self.comments_count = status.comments_count
        self.attitudes_count = status.attitudes_count
        
        //获取微博话题的属性文本
        self.huatiAtteibute = dealContentText(source: status.text!)
        self.zhuangfaAtt = dealContentText(source: ("@\(status.retweeted_status?.user?.name ?? ""):" + (status.retweeted_status?.text! ?? "")!) ?? "")
        
        setWeiBoSource()

    }
}

extension BPStatusCellViewModel {
    
    //处理微博来源
    //<a href="http://weibo.com/" rel="nofollow">微博 weibo.com</a>
    private func setWeiBoSource() {
        //将来源的字符串进行处理
        //设置开始和结束的字段
        let startFlag = "\">"
        let endFlag = "</"
        //获取需要截取的字符串
        let str = statusListModel?.source ?? ""
        
        //截取
        if let startRange = str.rangeOfString(startFlag),endRange = str.rangeOfString(endFlag) {
            
            let range = startRange.endIndex..<endRange.startIndex
            
            source = str.substringWithRange(range)
        }
    
    
    }
    
    
    //处理话题字符串
    private func dealContentText(source contentText: String) -> NSMutableAttributedString {
        let attStr = NSMutableAttributedString(string: contentText)
        
        dealWeiboText(parrentEnmotion, attStr: attStr)
        
        chouqu(parrentHuati,attStr: attStr)
        chouqu(parrentAt, attStr: attStr)
        chouqu(parrenturl, attStr: attStr)
        return attStr
        
    }
    
    private func chouqu(parrent: String, attStr:NSMutableAttributedString)  {
        //2.获取正则表达式
        let regex1 = try!NSRegularExpression(pattern: parrent, options: [])
        //3.执行表达式,获取结果,返回的是数组
        let result1 = regex1.matchesInString(attStr.string, options: [], range: NSRange(location: 0, length: attStr.string.characters.count))
        //3.1设置属性文本
        //let attStr = NSMutableAttributedString(string: contentText)
        //4.循环遍历,获取想要的字符串
        if result1.count > 0 {
            for res in result1.reverse() {
                let range = res.rangeAtIndex(0)
                _ = (attStr.string as NSString).substringWithRange(range)
                //4.1给属性文本设置对应的颜色的属性
                attStr.addAttribute(NSForegroundColorAttributeName, value: UIColor(red: 30 / 255.0, green: 128 / 255.0, blue: 183 / 255.0, alpha:1), range: range)
                
                //4.2设置文本的boder
                let boder = YYTextBorder(fillColor: UIColor(red: 30 / 255.0, green: 128 / 255.0, blue: 183 / 255.0, alpha:0.4), cornerRadius: 3)
                boder.insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
                //4.3设置文本高亮的模型
                let highlighted = YYTextHighlight()
                //4.4设置高亮状态下的颜色
                highlighted.setColor(UIColor.grayColor())
                //4.5设置背景色
                highlighted.setBackgroundBorder(boder)
                //4.6设置高亮的背景色
                attStr.yy_setTextHighlight(highlighted, range: range)
                
            }
        }

    }
    
    
    private func dealWeiboText(parrent: String, attStr:NSMutableAttributedString) {
        //2.获取正则表达式
        let regex1 = try!NSRegularExpression(pattern: parrent, options: [])
        //3.执行表达式,获取结果,返回的是数组
        let result1 = regex1.matchesInString(attStr.string, options: [], range: NSRange(location: 0, length: attStr.string.characters.count))
        //遍历数组  取出对应的range  截取子串
        let strM = attStr
        let text = strM.string
        //11代发货的北方[怒]大部分😄
        //倒序只需要替换一次就OK
        let textFont =  UIFont.systemFontOfSize(15)
        for res in result1.reverse() {
            let range = res.rangeAtIndex(0)
            let subStr = (text as NSString).substringWithRange(range)
            print(range,subStr)
            //获取了表情模型之后 可以将表情图片转换 属性字符串
            if let em = findEmoticonWithEmoticoText(subStr) {
                // [NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter]
                let image = UIImage(contentsOfFile: em.imagePath ?? "")
                let imageText = NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: .ScaleAspectFit, attachmentSize: CGSize(width: 15, height: 15), alignToFont: textFont, alignment: .Center)
                //将属性文本进行替换
                strM.replaceCharactersInRange(range, withAttributedString: imageText)
            }
        }
        
        //给属性文本添加对应的属性
        strM.addAttribute(NSFontAttributeName, value: textFont, range: NSRange(location: 0, length: strM.length))
        //设置属性文本的颜色
        strM.addAttribute(NSForegroundColorAttributeName, value: UIColor.darkGrayColor(), range: NSRange(location: 0, length: strM.length))
        
    }
    
    
    //根据表情字符串查找对应的表情模型  -> 获取表情图片的路径
    private func findEmoticonWithEmoticoText(subStr: String) -> HMEmoticon? {
        //1.获取表情数据源  获取分组表情模型
        for p in HMEmoticonManager.sharedEmoticon.packages {
            //获取每个cell对应的表情数组
            for emoticons in p.sectionEmoticon {
                //在数组中模型的chs == subStr
                let array = emoticons.filter({ (em) -> Bool in
                    return em.chs == subStr
                })
                
                if array.count != 0 {
                    return array.first
                }
            }
        }
        
        return nil
    }
    
    
    
    

}
